package com.hiwhitley.easy.day19;

/**
 * Created by hiwhitley on 2016/9/13.
 */
public class ZigZagConversion_6 {
    public static String convert(String s, int numRows) {
        if (numRows == 1)
            return s;
        StringBuilder strBuilder = new StringBuilder();
        int lengthOfGroup = 2 * numRows - 2;
        for (int row = 0; row < numRows; row++)
        {
            if (row == 0 || row == numRows - 1)
            {
                for (int j = row; j < s.length(); j += lengthOfGroup) {
                    strBuilder.append(s.charAt(j));
                }
            } else
            {
                int currentRow = row;
                int childLenOfGroup1 = 2 * (numRows - 1 - row);
                int childLenOfGroup2 = lengthOfGroup - childLenOfGroup1;

                boolean flag = true;
                while (currentRow < s.length()) {
                    strBuilder.append(s.charAt(currentRow));
                    if (flag)
                        currentRow += childLenOfGroup1;
                    else
                        currentRow += childLenOfGroup2;
                    flag = !flag;
                }
            }
        }
        return strBuilder.toString();
    }

    public static void main(String[] args) {
        System.out.println(convert("PAYPALISHIRING", 4));
    }
}
